package com.example.demo.core.service;
import com.example.demo.core.handlerMapping.handler.Handler;
import com.example.demo.core.handlerMapping.interfaces.HandlerMapping;
import com.example.demo.core.util.XmlUtil;
import gov.nist.javax.sip.message.SIPRequest;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Element;
import org.springframework.stereotype.Component;
import javax.sip.*;
import javax.sip.header.AuthorizationHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;

@Component
@Slf4j
public class SIPProcessorObserver implements SipListener {
    @Resource
    HandlerMapping handlerMapping;

    @Override
    public void processRequest(RequestEvent requestEvent) {
        Request request = requestEvent.getRequest();
        try {
            String messageType = handlerMapping.getMessageType(requestEvent);
            Handler handler = handlerMapping.getHandler(messageType);
            if (!handler.returnVoid){
                Response response = handler.invoke(requestEvent);
                SipProvider sipProvider = (SipProvider) requestEvent.getSource();
                ServerTransaction serverTransactionId = requestEvent.getServerTransaction() == null ?
                        sipProvider.getNewServerTransaction(request) : requestEvent.getServerTransaction();
                serverTransactionId.sendResponse(response);
            }else{
                handler.invoke(requestEvent);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void processResponse(ResponseEvent responseEvent) {
        Response response = responseEvent.getResponse();
        System.out.println(response);
    }

    @Override
    public void processTimeout(TimeoutEvent timeoutEvent) {

    }

    @Override
    public void processIOException(IOExceptionEvent ioExceptionEvent) {
        log.info("-------->processIOException:{}", ioExceptionEvent);
    }

    @Override
    public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
        log.info("-------->processTransactionTerminated:{}", transactionTerminatedEvent);
    }

    @Override
    public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
        log.info("-------->processDialogTerminated:{}", dialogTerminatedEvent);
    }

}
